package com.iipaas.twheel;

import java.util.Iterator;
import java.util.function.Consumer;

/**
 * 任务列表
 * @author tc
 */
public class Slot<T> implements Iterable<Task<T>> {
    private Task<T> head;
    private Task<T> end;
    private int length;

    public Slot() {
        init();
    }

    /**
     * 在队列尾追加数据
     * @param data 数据
     */
    public void add(T data, long timeout){
        Task<T> task;
        if (length == 0) {
            task = new Task<>(data, timeout);
            head = task;
        } else {
            task = new Task<>(data, timeout, null, end);
            end.setNext(task);
        }
        end = task;
        length ++;
    }

    /**
     * 清空队列
     */
    public void clear(){
        init();
    }

    /**
     * 获取队列长度
     * @return 长度
     */
    public int length() {
        return length;
    }

    /**
     * 初始化
     */
    private void init(){
        head = end = null;
        length = 0;
    }

    @Override
    public Iterator<Task<T>> iterator() {
        return new Iterator<Task<T>>() {
            private int cur = -1;
            private Task<T> curTask = new Task<>(null, 0, head, null);
            @Override
            public boolean hasNext() {
                return cur + 1 < length;
            }

            @Override
            public Task<T> next() {
                cur ++;
                curTask = curTask.getNext();
                return curTask;
            }
        };
    }

    @Override
    public void forEach(Consumer<? super Task<T>> action) {
        Iterable.super.forEach(action);
    }
}
